package com.transfiguro.visitors;

import com.transfiguro.datamodel.javamodels.Variable;
import japa.parser.ast.body.BodyDeclaration;
import japa.parser.ast.body.ClassOrInterfaceDeclaration;
import japa.parser.ast.body.FieldDeclaration;
import japa.parser.ast.body.VariableDeclarator;
import japa.parser.ast.visitor.VoidVisitorAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * This class provides methods to visit different variables declared in a given class
 */
public class ClassVarVisitor extends VoidVisitorAdapter {
    private List<Variable> variableList;
    private ClassOrInterfaceDeclaration ciDeclaration;

    /**
     * Constructor
     */
    public ClassVarVisitor() {
        variableList = new ArrayList<Variable>();
    }

    /**
     * This method is the starting point for the process of getting the different
     * variables declared in the class outside the methods
     *
     * @param ciDeclaration  The <code>ClassOrInterfaceDeclaration</code> which has to be parsed
     */
    public void getVars(final ClassOrInterfaceDeclaration ciDeclaration) {
        for (final BodyDeclaration bodyDeclaration : ciDeclaration.getMembers()) {
            if (bodyDeclaration instanceof FieldDeclaration) {
                visit((FieldDeclaration) bodyDeclaration, null);
            }
        }
    }

    /**
     * This method visits the individual {@link FieldDeclaration}s in the given class
     *
     * @param fieldDeclaration  The <code>FieldDeclaration</code> that has to be parsed to get the
     *                         different variables in the class
     * @param arg               Optional argument that can be used to pass anything into the function
     */
    @Override
    public void visit(final FieldDeclaration fieldDeclaration, final Object arg) {
        final String type = fieldDeclaration.getType().toString();
        for (final VariableDeclarator variableDeclarator : fieldDeclaration.getVariables()) {
            Variable variable = new Variable();
            variable.setAccessModifier(fieldDeclaration.getModifiers());
            variable.setVariableName(variableDeclarator.getId().getName());
            variable.setType(type);
            variableList.add(variable);
        }


    }

    /**
     * Getter for <code>variableList</code>
     *
     * @return  The list of <code>variables</code> created by visiting the
     *         variables in the given class
     */
    public List<Variable> getVariableList() {
        return variableList;
    }
}
